//
//  CAMineController.m
//  cascade-realm
//
//  Created by QSC on 20/5/24.
//

#import "CAMineController.h"
#import "CASettingController.h"
#import "CAUserInfoController.h"
#import "CAHomeCollectionCell.h"
#import "CACoinCoutroller.h"
#import "CAFollowListController.h"
#import "CADetailController.h"
#import "CAAboutCoutroller.h"
@interface CAMineController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong)UIImageView * bgImgv;
@property (nonatomic,strong)UIImageView * headImgv;
@property (nonatomic,strong)UILabel * nameLabel;
@property (nonatomic,strong)UIView* InfoView;
@property (nonatomic,strong)UIView* centerTitleView;
@property (nonatomic,strong)UIView* coinView;
@property (nonatomic,assign)NSInteger titleIndex;
@property (nonatomic,strong)UICollectionView * collectionView;
@property (nonatomic,strong)UIImageView * emptyImageV;
@property (nonatomic,strong)NSMutableArray * createArray;
@property (nonatomic,strong)NSMutableArray * favorieArray;

@property (nonatomic,strong)NSMutableArray * followArray;
@property (nonatomic,strong)NSMutableArray * blockArray;
@property (nonatomic,strong)UILabel* followLabel;
@property (nonatomic,strong)UILabel * blockLabel;
@property (nonatomic,strong)UILabel * coinLabel;
@end

@implementation CAMineController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navView.hidden = YES;
    
    [self setUpView];
}




- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [Tool colorGradientLayerForView:self.coinView frame:self.coinView.bounds colors:@[Hex(0xE0FA83),Hex(0xD4E600)] locations:@[@0.0,@1.0]];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear: animated];
    
    
    [self.bgImgv sd_setImageWithURL:[NSURL URLWithString:[CAUserInfo shared].userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")];
    [self.headImgv sd_setImageWithURL:[NSURL URLWithString:[CAUserInfo shared].userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")];
    self.nameLabel.text = [CAUserInfo shared].userInfo.nickname;
    self.coinLabel.text = [CAUserInfo shared].userInfo.availableCoins;
    
    
    [self getDataArray];
    
    
    [self refreshFollowAndBlock];
    
}

- (void)getDataArray{
    NSString * k = [NSString stringWithFormat:@"%@--islike",CAUserInfo.shared.userInfo.userId];
    NSDictionary * dic = [DBTool getData:k];
    NSArray * arr = dic[@"islike"];
    self.favorieArray = [NSMutableArray array];
    for (NSString * str in arr) {
        
        NSDictionary * dic = [DBTool getData:str];
        
        CADataModel * model = [CADataModel mj_objectWithKeyValues:dic];
        [self.favorieArray addObject:model];
        
    }
    
    
    self.createArray = [CADataModel getPuhlishAtticle];
    
    //reload
    self.titleIndex = self.titleIndex;
}


//请求关注和拉黑列表
- (void)refreshFollowAndBlock{
    
    NSDictionary * dic = @{@"limit":@"100",@"page":@"1"};
    
    [Http postWithURL:getFriendsListPage params:dic isShowHud:NO isLogin:NO success:^(id  _Nonnull responseObject) {
        
        self.followArray = [CAHomeUser mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        self.followLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.followArray.count];
            
    } failure:^(id  _Nonnull errObject) {
        
    }];
    
    [Http postWithURL:getblockList params:@{} isShowHud:NO isLogin:NO success:^(id  _Nonnull responseObject) {
        
        self.blockArray = [CAHomeUser mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        self.blockLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.blockArray.count];
            
    } failure:^(id  _Nonnull errObject) {
        
    }];
    
    
    
}


- (void)setUpView{
    
    UIImageView * bgImgv = [UIImageView new];

    
    [bgImgv sd_setImageWithURL:[NSURL URLWithString:[CAUserInfo shared].userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")];
    // 毛玻璃效果的style
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
    // 毛玻璃视图
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    // addSubview
    [bgImgv addSubview:visualView];
    [visualView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bgImgv);
    }];

    
    [self.view addSubview:bgImgv];
    [bgImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(230);
    }];
    
    UIButton * settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingBtn setImage:Img(@"mine_setting") forState:UIControlStateNormal];
    [self.view addSubview:settingBtn];
    [settingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(28);
        make.right.equalTo(self.view).offset(-20);
        make.top.equalTo(self.view).offset(KNavigationStatusHeight + 8);
    }];
    [settingBtn addTarget:self action:@selector(settingClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [infoBtn setImage:Img(@"mine_info") forState:UIControlStateNormal];
    [self.view addSubview:infoBtn];
    [infoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(28);
        make.right.equalTo(settingBtn.mas_left).offset(-24);
        make.centerY.equalTo(settingBtn);
    }];

    [infoBtn addTarget:self action:@selector(aboutClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * infoView = [UIView new];
    infoView.backgroundColor = [UIColor whiteColor];
    infoView.layer.cornerRadius = 8;
    infoView.backgroundColor = [UIColor whiteColor];
    [infoView setDefultBorder];
    [self.view addSubview:infoView];
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(bgImgv.mas_bottom).offset(-100);
    }];
    self.InfoView = infoView;
    
    [self setUpInfoView];
    
    [self setTitlesView];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(self.centerTitleView.mas_bottom).offset(10);
        make.bottom.equalTo(self.view).offset(-kTabBarHeight -10);
    }];
    
    self.emptyImageV = [[UIImageView alloc] initWithImage:Img(@"mine_empty")];
    [self.collectionView addSubview:self.emptyImageV];
    [self.emptyImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.collectionView);
        make.size.mas_equalTo(200);
        make.centerY.equalTo(self.collectionView).offset(-50);
    }];
    self.titleIndex = 0;
}


- (void)setUpInfoView{
    
    UIImageView * headImgv = [UIImageView new];
    headImgv.layer.cornerRadius = 44;
    headImgv.clipsToBounds = YES;
    [self.InfoView addSubview:headImgv];
    headImgv.backgroundColor = [UIColor lightGrayColor];
    [headImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.InfoView).offset(-29);
        make.left.equalTo(self.InfoView).offset(21);
        make.size.mas_equalTo(88);
    }];
    self.headImgv = headImgv;
   
    [headImgv sd_setImageWithURL:[NSURL URLWithString:[CAUserInfo shared].userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")];
    
    UILabel * nameLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x202020) text:[CAUserInfo shared].userInfo.nickname];
    self.nameLabel = nameLabel;
    UIButton * editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [editBtn setImage:Img(@"mine_edit") forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(infoClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.InfoView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headImgv.mas_right).offset(12);
        make.top.equalTo(self.InfoView).offset(12);
    }];
    
    [self.InfoView addSubview:editBtn];
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel);
        make.left.equalTo(nameLabel.mas_right).offset(11);
        make.size.mas_equalTo(16);
    }];
    
    UILabel * IDlabel = [UILabel LabelWithFont:Font(14) color:[Hex(0x000000) colorWithAlphaComponent:0.3] text:[NSString stringWithFormat:@"ID:%@",[CAUserInfo shared].userInfo.showID]];
    UIButton * copyBtn = [UIButton ButtonWithFont:Font(10) color:[UIColor whiteColor] text:@"copy"];
    copyBtn.backgroundColor = Hex(0x8FD045);
    copyBtn.layer.cornerRadius = 6;
    [self.InfoView addSubview:IDlabel];
    [self.InfoView addSubview:copyBtn];
    
    [IDlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.bottom.equalTo(headImgv);
    }];
    
    [copyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(IDlabel);
        make.left.equalTo(IDlabel.mas_right).offset(6);
        make.height.mas_equalTo(12);
    }];
    
    [copyBtn addTarget:self action:@selector(copyClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * coinView = [UIView new];
    coinView.layer.cornerRadius = 8;
    coinView.clipsToBounds = true;
    coinView.layer.borderWidth = 1;
    coinView.layer.borderColor = Hex(0xB3E600).CGColor;
    self.coinView = coinView;
    [self.InfoView addSubview:coinView];
    [coinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.InfoView).inset(15);
        make.top.equalTo(headImgv.mas_bottom).offset(24);
        make.height.mas_equalTo(40);
    }];
    WeakSelf
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf.navigationController pushViewController:[CACoinCoutroller new] animated:YES];
    }];
    [coinView addGestureRecognizer:tap];
    
    
    UIImageView * coinImg = [[UIImageView alloc] initWithImage:Img(@"mine_coins")];
    [coinView addSubview:coinImg];
    [coinImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(coinView);
        make.left.equalTo(coinView).offset(16);
        make.size.mas_equalTo(27);
    }];
    
    UILabel * coinLabel = [UILabel LabelWithFont:Font(15) color:Hex(0x1A3710) text:[CAUserInfo shared].userInfo.availableCoins];
    [coinView addSubview:coinLabel];
    self.coinLabel = coinLabel;
    [coinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(coinView);
        make.left.equalTo(coinImg.mas_right).offset(10);
    }];
    
    UIButton * coinBtn = [UIButton ButtonWithFont:Font(12) color:Hex(0x657C47) text:@"coins"];
    coinBtn.userInteractionEnabled = NO;
    coinBtn.layer.cornerRadius = 10;
    [coinView addSubview:coinBtn];
    coinBtn.backgroundColor = [UIColor whiteColor];
    [coinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(coinView);
        make.right.equalTo(coinView).offset(-12);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(53);
    }];
    
    UIControl * followBtn = [self FollowAndBlocktext:@"Following"];
    UIControl * BlockBtn = [self FollowAndBlocktext:@"Block"];
    
    [self.InfoView addSubview:followBtn];
    [self.InfoView addSubview:BlockBtn];

    [followBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.InfoView).offset(52);
        make.top.equalTo(coinView.mas_bottom).offset(24);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(50);
    }];
    
    [BlockBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.InfoView).offset(-52);
        make.top.equalTo(coinView.mas_bottom).offset(24);
        make.bottom.equalTo(self.InfoView).offset(-16);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(50);
    }];
    
    [followBtn addTarget:self action:@selector(followClick) forControlEvents:UIControlEventTouchUpInside];
    [BlockBtn addTarget:self action:@selector(blockClick) forControlEvents:UIControlEventTouchUpInside];
   
}

- (void)setTitlesView{
    
    UIView *centerTitleView = [UIView new];
    [self.view addSubview:centerTitleView];
    [centerTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.InfoView.mas_bottom).offset(10);
        make.height.mas_equalTo(50);
    }];
    self.centerTitleView = centerTitleView;
    
    UILabel * createLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x404040) text:@"Creations"];

    UILabel * FavorLabel = [UILabel LabelWithFont:Font(16) color:[[UIColor blackColor] colorWithAlphaComponent:0.5] text:@"Favorite"];
    
    [centerTitleView addSubview:createLabel];
    [centerTitleView addSubview:FavorLabel];
    createLabel.userInteractionEnabled = YES;
    FavorLabel.userInteractionEnabled = YES;
    [createLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(centerTitleView);
        make.left.equalTo(centerTitleView).offset(20);
    }];
    
    [FavorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(centerTitleView);
        make.left.equalTo(createLabel.mas_right).offset(40);
    }];
    
    UIView *lineView = [UIView new];
    lineView.layer.cornerRadius = 4;

    [Tool colorGradientLayerForView:lineView frame:CGRectMake(0, 0, 55, 8) colors:@[Hex(0xCEF568),[Hex(0xCEF568) colorWithAlphaComponent:0.1]] locations:@[@0.0,@1.0]];
    [centerTitleView insertSubview:lineView atIndex:0];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(createLabel);
        make.bottom.equalTo(createLabel);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(8);
    }];
    
    [createLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        if(self.titleIndex == 0){return;}
    
        [UIView animateWithDuration:0.3 animations:^{
            [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(createLabel);
                make.bottom.equalTo(createLabel);
                make.width.mas_equalTo(55);
                make.height.mas_equalTo(8);
            }];
            
            [centerTitleView layoutIfNeeded];
        }];
        self.titleIndex = 0;
        createLabel.textColor = Hex(0x404040);
        FavorLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }]];
    
    
    [FavorLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        if(self.titleIndex == 1){return;}
        
    
        [UIView animateWithDuration:0.3 animations:^{
            [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(FavorLabel);
                make.bottom.equalTo(createLabel);
                make.width.mas_equalTo(55);
                make.height.mas_equalTo(8);
            }];
            [centerTitleView layoutIfNeeded];
        }];
        self.titleIndex = 1;
        FavorLabel.textColor = Hex(0x404040);
        createLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }]];

}

- (void)setTitleIndex:(NSInteger)titleIndex{
    
    _titleIndex = titleIndex;
    if (titleIndex == 0) {
      
        self.emptyImageV.hidden = self.createArray.count != 0;
        
    }
    
    if (titleIndex == 1) {
        self.emptyImageV.hidden = self.favorieArray.count != 0;
        
    }
    [self.collectionView reloadData];
    
}



- (void)settingClick{
   
    [self.navigationController pushViewController:[CASettingController new] animated:YES];
}

- (void)aboutClick{
    

    [self.navigationController pushViewController:[CAAboutCoutroller new] animated:YES];
}


- (void)infoClick{
  
    [self.navigationController pushViewController:[CAUserInfoController new] animated:YES];
}

- (void)copyClick{
    UIPasteboard * pad = [UIPasteboard generalPasteboard];
    pad.string = [CAUserInfo shared].userInfo.showID;
    [EasyTextView showText:@"Copied to the clipboard"];
}


- (UIControl *)FollowAndBlocktext:(NSString *)text{
    UIControl * btn = [UIControl new];
    UILabel * numLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x565656) text:@"0"];
    UILabel * textLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x565656) text:text];

    [btn addSubview:numLabel];
    [btn addSubview:textLabel];
    [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(btn);
        make.top.equalTo(btn).offset(5);
    }];
    
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(btn);
        make.top.equalTo(numLabel.mas_bottom).offset(5);
    }];
    
    if([text isEqualToString:@"Block"]){
        self.blockLabel = numLabel;
    }else{
        self.followLabel = numLabel;
    }
  
    
    return btn;
}






- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat itmeW = (ScreenW - 40 - 15) / 2;
        layout.itemSize = CGSizeMake(itmeW , itmeW/162 * 204);
        
        layout.minimumInteritemSpacing = 15;

        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        
        [collectionView registerClass:[CAHomeCollectionCell class] forCellWithReuseIdentifier:@"CAHomeCollectionCell"];
        // 去掉滚动条
        collectionView.showsVerticalScrollIndicator = NO;
     
        collectionView.bounces = NO;
        _collectionView = collectionView;
    }
    return  _collectionView;;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.titleIndex == 0) {
        return self.createArray.count;
    }else{
        return self.favorieArray.count;
    }
    

  
}


- (UICollectionViewCell *)collectionView:(UICollectionView *) collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    CAHomeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CAHomeCollectionCell" forIndexPath:indexPath];
    CADataModel * model = nil;
    if (self.titleIndex == 0) {
        model = self.createArray[indexPath.row];
    }else{
        model = self.favorieArray[indexPath.row];
    }
    cell.model = model;
    cell.inMineView = YES;
    WeakSelf
    cell.rightClick = ^{
        
        [Tool ShowLoading];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [Tool HideLoading];
            if(weakSelf.titleIndex == 0){
                
                [model removeFormPublishArticle];
                
            }else{
                
                [model SetIslikeInDB:NO];
               
            }
            [weakSelf getDataArray];
            [EasyTextView showText:@"Delete Success"];
        });
        
 
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CADataModel * model = nil;
    if (self.titleIndex == 0) {
        model = self.createArray[indexPath.row];
    }else{
        model = self.favorieArray[indexPath.row];
    }
    CADetailController * vc = [CADetailController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
    
}




- (void)followClick{
    CAFollowListController *vc = [CAFollowListController new];
    vc.dataArray = self.followArray;
    vc.type = 1;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)blockClick{
    CAFollowListController *vc = [CAFollowListController new];
    vc.dataArray = self.blockArray;
    vc.type = 2;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
